// 页面加载时执行
document.addEventListener('DOMContentLoaded', function() {
    // 设置日期选择器的最小日期为明天
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    document.getElementById('examDate').min = tomorrow.toISOString().split('T')[0];

    // 初始化页面
    initPage();
});

// API地址
const API_URL = {
    getPackages: '/api/physical-exam/packages',  // 获取体检套餐API
    createAppointment: '/api/physical-exam/appointments',  // 创建体检预约API
    getAvailableSlots: '/api/physical-exam/available-slots'  // 获取可用时段API
};

// 初始化页面
async function initPage() {
    try {
        // 从后端获取体检套餐信息
        const packageData = await fetchPackageDetails();
        
        // 保存套餐数据到全局变量
        window.packageDetails = packageData;
        
        // 初始化显示基础套餐详情
        updatePackageContent('basic');
        
        // 更新套餐下拉菜单
        updatePackageDropdown(packageData);
        
        // 为套餐标签添加点击事件
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', function() {
                // 移除所有标签的active类
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                // 为当前标签添加active类
                this.classList.add('active');
                // 更新套餐内容
                updatePackageContent(this.dataset.package);
            });
        });
        
        // 添加日期选择事件监听
        document.getElementById('examDate').addEventListener('change', async function() {
            if (this.value) {
                await updateAvailableTimeSlots(this.value);
            }
        });
    } catch (error) {
        console.error('初始化页面失败:', error);
        // 使用本地数据作为备用
        useLocalPackageData();
    }
}

// 获取体检套餐详情
async function fetchPackageDetails() {
    try {
        const response = await fetch(API_URL.getPackages, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            credentials: 'include' // 包含cookies等凭证
        });

        if (!response.ok) {
            if (response.status === 401 || response.status === 403) {
                window.location.href = '../login.html'; // 未登录时重定向
                throw new Error('未登录或无权限');
            }
            throw new Error('服务器响应异常: ' + response.status);
        }

        const result = await response.json();
        
        // 处理后端返回的标准格式R<T>响应
        if (result.code === 1 && result.data) {
            return result.data;
        } else {
            throw new Error(result.msg || '获取体检套餐信息失败');
        }
    } catch (error) {
        console.error('获取体检套餐API请求失败:', error);
        throw error;
    }
}

// 获取可用时间段
async function fetchAvailableTimeSlots(date) {
    try {
        const response = await fetch(`${API_URL.getAvailableSlots}?date=${encodeURIComponent(date)}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            credentials: 'include' // 包含cookies等凭证
        });

        if (!response.ok) {
            throw new Error('服务器响应异常: ' + response.status);
        }

        const result = await response.json();
        
        // 处理后端返回的标准格式R<T>响应
        if (result.code === 1 && result.data) {
            return result.data;
        } else {
            throw new Error(result.msg || '获取可用时间段失败');
        }
    } catch (error) {
        console.error('获取可用时间段API请求失败:', error);
        throw error;
    }
}

// 使用本地体检套餐数据（备用方案）
function useLocalPackageData() {
    console.log('使用本地套餐数据');
    window.packageDetails = {
        basic: {
            id: 1,
            code: 'basic',
            name: '基础体检套餐',
            price: 299,
            items: [
                "一般体格检查",
                "血常规",
                "尿常规",
                "肝功能",
                "血脂四项",
                "心电图"
            ]
        },
        advanced: {
            id: 2,
            code: 'advanced',
            name: '高级体检套餐',
            price: 599,
            items: [
                "一般体格检查",
                "血常规",
                "尿常规",
                "肝功能",
                "血脂四项",
                "心电图",
                "胸部X光",
                "B超（肝胆胰脾）",
                "甲状腺功能"
            ]
        },
        premium: {
            id: 3,
            code: 'premium',
            name: '精密体检套餐',
            price: 999,
            items: [
                "一般体格检查",
                "血常规",
                "尿常规",
                "肝功能",
                "血脂四项",
                "心电图",
                "胸部X光",
                "B超（肝胆胰脾）",
                "甲状腺功能",
                "颈动脉彩超",
                "肿瘤标志物",
                "骨密度检测",
                "幽门螺杆菌检测"
            ]
        }
    };
    
    // 更新套餐下拉菜单
    updatePackageDropdown(window.packageDetails);
    
    // 初始化显示基础套餐详情
    updatePackageContent('basic');
    
    // 显示离线提示
    showToast('当前使用离线数据，部分功能可能受限');
}

// 更新套餐下拉菜单
function updatePackageDropdown(packageData) {
    const select = document.getElementById('examPackage');
    select.innerHTML = '<option value="">请选择套餐</option>';
    
    for (const key in packageData) {
        const pkg = packageData[key];
        const option = document.createElement('option');
        option.value = key;
        option.textContent = `${pkg.name} (${pkg.price}元)`;
        select.appendChild(option);
    }
}

// 更新可用时间段
async function updateAvailableTimeSlots(date) {
    const timeSelect = document.getElementById('examTime');
    
    // 显示加载状态
    timeSelect.disabled = true;
    timeSelect.innerHTML = '<option value="">加载中...</option>';
    
    try {
        // 获取所选日期可用的时间段
        const availableSlots = await fetchAvailableTimeSlots(date);
        
        // 重置下拉菜单
        timeSelect.innerHTML = '<option value="">请选择时段</option>';
        
        // 检查上午时段是否可用
        if (availableSlots.morning_available) {
            const morningOption = document.createElement('option');
            morningOption.value = 'morning';
            morningOption.textContent = '上午 (8:00-11:00)';
            timeSelect.appendChild(morningOption);
        }
        
        // 检查下午时段是否可用
        if (availableSlots.afternoon_available) {
            const afternoonOption = document.createElement('option');
            afternoonOption.value = 'afternoon';
            afternoonOption.textContent = '下午 (14:00-16:00)';
            timeSelect.appendChild(afternoonOption);
        }
        
        // 如果没有可用时段
        if (!availableSlots.morning_available && !availableSlots.afternoon_available) {
            const noOptionAvailable = document.createElement('option');
            noOptionAvailable.value = "";
            noOptionAvailable.textContent = '当天无可用时段';
            noOptionAvailable.disabled = true;
            timeSelect.appendChild(noOptionAvailable);
        }
    } catch (error) {
        console.error('获取可用时间段失败:', error);
        
        // 出错时显示默认选项
        timeSelect.innerHTML = `
            <option value="">请选择时段</option>
            <option value="morning">上午 (8:00-11:00)</option>
            <option value="afternoon">下午 (14:00-16:00)</option>
        `;
    } finally {
        // 恢复下拉菜单可用状态
        timeSelect.disabled = false;
    }
}

// 更新套餐内容的函数
function updatePackageContent(packageType) {
    if (!window.packageDetails || !window.packageDetails[packageType]) {
        console.error('套餐信息不存在:', packageType);
        return;
    }
    
    const content = document.getElementById('packageContent');
    const items = window.packageDetails[packageType].items;
    
    content.innerHTML = `
        <ul style="list-style-type: none; padding: 0;">
            ${items.map(item => `
                <li style="margin-bottom: 10px; color: #666;">
                    <i class="fas fa-check" style="color: #4CAF50; margin-right: 10px;"></i>
                    ${item}
                </li>
            `).join('')}
        </ul>
    `;
}

// 提交预约
function submitAppointment() {
    const date = document.getElementById('examDate').value;
    const time = document.getElementById('examTime').value;
    const packageCode = document.getElementById('examPackage').value;

    // 验证表单
    if (!date) {
        showToast('请选择预约日期');
        return;
    }
    if (!time) {
        showToast('请选择预约时段');
        return;
    }
    if (!packageCode) {
        showToast('请选择体检套餐');
        return;
    }

    // 显示确认弹窗
    const modal = document.getElementById('confirmModal');
    const packageData = window.packageDetails[packageCode];
    const timeText = time === 'morning' ? '上午 (8:00-11:00)' : '下午 (14:00-16:00)';
    
    document.getElementById('confirmDate').textContent = `预约日期：${date}`;
    document.getElementById('confirmTime').textContent = `预约时段：${timeText}`;
    document.getElementById('confirmPackage').textContent = `体检套餐：${packageData.name} (${packageData.price}元)`;

    modal.style.display = 'flex';
}

// 隐藏确认弹窗
function hideConfirmModal() {
    document.getElementById('confirmModal').style.display = 'none';
}

// 确认预约
async function confirmAppointment() {
    const date = document.getElementById('examDate').value;
    const time = document.getElementById('examTime').value;
    const packageCode = document.getElementById('examPackage').value;
    
    // 禁用确认按钮，防止重复提交
    const confirmButton = document.querySelector('.btn-confirm');
    const originalText = confirmButton.textContent;
    confirmButton.disabled = true;
    confirmButton.textContent = '提交中...';
    
    try {
        // 准备提交的数据
        const appointmentData = {
            appointment_date: date,
            time_slot: time,
            package_code: packageCode
        };
        
        // 发送请求到后端API
        const result = await createAppointment(appointmentData);
        
        // 隐藏弹窗
        hideConfirmModal();
        
        // 显示成功提示
        showToast('预约成功！我们会通过短信通知您具体体检安排。');
        
        // 重置表单
        document.getElementById('examDate').value = '';
        document.getElementById('examTime').value = '';
        document.getElementById('examPackage').value = '';
        
    } catch (error) {
        console.error('预约失败:', error);
        hideConfirmModal();
        showToast('预约失败：' + (error.message || '网络错误，请稍后再试'));
    } finally {
        // 恢复按钮状态
        confirmButton.disabled = false;
        confirmButton.textContent = originalText;
    }
}

// 创建体检预约
async function createAppointment(appointmentData) {
    try {
        const response = await fetch(API_URL.createAppointment, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            credentials: 'include', // 包含cookies等凭证
            body: JSON.stringify(appointmentData)
        });

        if (!response.ok) {
            if (response.status === 401 || response.status === 403) {
                window.location.href = '../login.html'; // 未登录时重定向
                throw new Error('未登录或无权限');
            }
            throw new Error('服务器响应异常: ' + response.status);
        }

        const result = await response.json();
        
        // 处理后端返回的标准格式R<T>响应
        if (result.code === 1) {
            return result.data;
        } else {
            throw new Error(result.msg || '预约失败');
        }
    } catch (error) {
        console.error('创建预约API请求失败:', error);
        throw error;
    }
}

// 显示toast提示
function showToast(message) {
    // 检查是否已存在toast元素
    let toast = document.getElementById('toast');
    if (!toast) {
        // 创建toast元素
        toast = document.createElement('div');
        toast.id = 'toast';
        toast.style.position = 'fixed';
        toast.style.bottom = '30px';
        toast.style.left = '50%';
        toast.style.transform = 'translateX(-50%)';
        toast.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
        toast.style.color = 'white';
        toast.style.padding = '12px 20px';
        toast.style.borderRadius = '4px';
        toast.style.zIndex = '1000';
        toast.style.transition = 'opacity 0.3s';
        document.body.appendChild(toast);
    }
    
    // 设置消息并显示
    toast.textContent = message;
    toast.style.opacity = '1';
    
    // 3秒后隐藏
    setTimeout(() => {
        toast.style.opacity = '0';
    }, 3000);
}